package com.htthorizon.powersupply.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htthorizon.powersupply.domain.TgVoltMonitor;
import com.htthorizon.powersupply.dto.TgLowVoltItem;
import com.htthorizon.powersupply.dto.VoltTgItem;
import com.htthorizon.powersupply.mapper.TgVoltMonitorMapper;
import com.htthorizon.powersupply.search.VoltTgSearch;
import com.htthorizon.powersupply.service.TgVoltMonitorService;
import com.htthorizon.powersupply.utils.OrgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
* @author Brilliant
* @description 针对表【tg_volt_monitor】的数据库操作Service实现
* @createDate 2025-01-17 16:55:14
*/
@Service
public class TgVoltMonitorServiceImpl extends ServiceImpl<TgVoltMonitorMapper, TgVoltMonitor>
    implements TgVoltMonitorService{

    @Autowired
    private TgVoltMonitorMapper tgVoltMonitorMapper;


    @Override
    public List<TgLowVoltItem> getStatistics(String type, Integer maxTime, String dataDt) {
        List<TgLowVoltItem> statistics = tgVoltMonitorMapper.getStatistics(type, maxTime, dataDt);
        if (statistics.isEmpty()) {
            return statistics;
        }else{
            statistics.forEach(item -> {
                item.setStdOrgNm(OrgUtil.getStdOrgNm(item.getStdOrgNm()));
            });
        }
        String format = getPreviousDayStartFormatted();
        List<TgLowVoltItem> statistics2=  tgVoltMonitorMapper.getUsersCount(statistics,format);
        for (TgLowVoltItem item : statistics) {
            for (TgLowVoltItem item2 : statistics2) {
                if (item.getLineNm().equals(item2.getLineNm())){
                    item.setUserCount(item2.getUserCount());
                    item.setStdOrgNm(OrgUtil.getStdOrgNm(item.getStdOrgNm()));
                    break;
                }
            }
        }
        return statistics;
    }

    @Override
    public List<VoltTgItem> getVoltTgItems(VoltTgSearch search,String type, Integer maxTime, String dataDt) {
        return tgVoltMonitorMapper.getVoltTgItems(search,type, maxTime, dataDt);
    }

    @Override
    public Integer getMaxTime(String dateDt) {
        return tgVoltMonitorMapper.getMaxTime(dateDt);
    }

    public static String getPreviousDayStartFormatted() {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 将日期往前推一天
        LocalDateTime previousDay = now.minusDays(1);
        // 将时分秒置为 0
        LocalDateTime previousDayStart = previousDay.withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 定义日期时间格式化的模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 对处理好的日期时间进行格式化，并返回格式化后的字符串
        return previousDayStart.format(formatter);
    }
}




